﻿using CommandService;
using Entity;
using Entity.DbEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Entity.FrameEntity;
using System.Threading;
using Tools;
using System.Reflection;
using SysFramework;
using log4net;

namespace BLL
{
    /// <summary>
    /// 接口服务逻辑处理层
    /// </summary>
    public class ServiceBLL : PubMethod
    {
        HttpAgreement http;
        Commands cmd;
        ReturnResult rsl;
        OutBaseHelper outBase;
        BarBLL barBLL;
        U8Order uOrder;
        StringBuilder sb = new StringBuilder();
        ILog _log;

        public ServiceBLL()
        {
            http = new HttpAgreement();
            cmd = new Commands();
            outBase = new OutBaseHelper();
            barBLL = new BarBLL();
            uOrder = new U8Order();
            _log = LogManager.GetLogger(this.GetType().Name);
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult updateUserPassword(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                #region 修改用户密码
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "传递参数不允许为空";
                    return rsl;
                }
                #region 解密
                jsonStr = Encryption.DesDecrypt(jsonStr);
                #endregion
                var json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                var oldpwd = json["oldPassword"].ToString();
                var newpwd = json["newPassword"].ToString();  //新密码
                string enpwd = Tools.Encryption.MD5Encode(oldpwd);
                var jmPwd = Tools.Encryption.MD5Encode(newpwd);
                string userCode = json["userCode"].ToString();
                string sql = "select * from sys_users_info where userCode='" + userCode + "'";
                var table = cmd.GetDataTable(sql);
                if (table.Rows.Count < 1)
                {
                    rsl.Message = "无法获取账号信息";
                    return rsl;
                }
                if (table.Rows[0]["userPwd"].ToString() != enpwd)
                {
                    rsl.Message = "当前密码输入错误";
                    return rsl;
                }
                sql = "update sys_users_info set userPwd='" + jmPwd + "',openpwd='" + newpwd + "' where userCode='" + userCode + "'";
                rsl = cmd.UpdateSql(sql);
                #endregion
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 验证扫描条码是否有效(应用范围：移动端)
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult CheckBarCode(string barCode, Dictionary<string, string> tempDic)
        {
            rsl = new ReturnResult();
            try
            {
                var inOutType = tempDic["inOutType"].ToString();
                var baseCode = tempDic["baseCode"].ToString();
                StringBuilder sb = new StringBuilder();
                if (inOutType != null && !string.IsNullOrWhiteSpace(inOutType))
                {
                    if ((inOutType.Equals("pibg") || inOutType.Equals("pobg")))
                    {
                        //版辊信息
                        sb.Append(" select top 1 *,status barStatus,'1' number from fun_BanYang_list ");
                        sb.Append("where dTypes='bg' and byBarCode='" + barCode + "' and baseCode='" + baseCode + "'");
                        sb.Append("  and isdel=0 ");
                    }
                    else if ((inOutType.Equals("piyb") || inOutType.Equals("poyb")))
                    {
                        //sb.Append(" select top 1 * from V_YangBan_info ");
                        //sb.Append("where yCode='" + barCode + "' ");
                        //sb.Append("  and isdel=0 ");
                    }
                    else
                    {
                        sb.Append("select top 1 * from V_BarCode_Info ");//非箱码
                        sb.Append("where barCode='" + barCode + "'");
                    }
                }
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "此码系统不存在";
                    rsl.Result = false;
                }
            }
            catch (Exception ex)
            {
                rsl.Result = false;
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 验证条码是否已经扫描(出入库)
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult CheckRepeatTempBar(string jsonStr)
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "传递参数有误";
                    return rsl;
                }
                var obj = JsonConvert.DeserializeObject<JObject>(jsonStr);
                sb = new StringBuilder();
                sb.Append("select top 1 barCode from bar_TempScanData_info where 1=1");
                if (obj.Property("tempCode") != null)
                {
                    sb.Append(" and tempCode='" + obj["tempCode"].ToString() + "'  ");
                }
                //if (isBoxCode(obj["barCode"].ToString()))
                //{
                //    sb.Append("  boxCode='" + obj["barCode"] + "'");
                //}
                //else
                //{
                    
                //}
                sb.Append(" and barCode='" + obj["barCode"].ToString() + "'");

                if (!string.IsNullOrWhiteSpace(obj["operateType"].ToString()))
                {
                    sb.Append(" and operateType='" + obj["operateType"].ToString() + "'");
                }
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Result = true;
                //如果有数据就为1
                if (table.Rows.Count > 0)
                {
                    rsl.Data = 1;
                }
                else
                {//没有数据就显示为0
                    rsl.Data = 0;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 添加扫码记录
        /// </summary>
        /// <param name="jsonStr">json串</param>
        /// <param name="number">重量</param>
        /// <returns></returns>
        public ReturnResult AddScanTempRecord(string number, string jsonStr, ref List<OperateModel> operList)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                DbTempScanData scan;
                //List<OperateModel> operList = new List<OperateModel>();
                OperateModel oper;
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Result = false;
                    rsl.Message = "参数不允许为空";
                    return rsl;
                }
                var json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                var scanTable = new DataTable();
                
                if (json["operateType"].ToString().Equals("01") || json["operateType"].ToString().Equals("02"))
                {
                    #region 防错验证
                    if (string.IsNullOrWhiteSpace(json["tempCode"].ToString()))
                    {
                        rsl.Result = false;
                        rsl.Message = "临时编码不允许为空";
                        return rsl;
                    }

                    #endregion

                    sb.Append("select barCode,createuser from  bar_TempScanData_info ");
                    sb.Append("where tempCode='" + json["tempCode"].ToString() + "'");
                    scanTable = cmd.GetDataTable(sb.ToString());//获取扫描单下的所有扫描记录    
                }

                #region 非箱码
                scan = new DbTempScanData();
                scan = JsonConvert.DeserializeObject<DbTempScanData>(jsonStr);
                scan.barCode = json["barCode"].ToString();
                scan.id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                scan.iQuantity = "1";//件数
                scan.number = number;//主计量数量
                scan.inOutType = json["inOutType"].ToString();

                // 版辊出入库类型 取 物控系统的   U8操作类型参数里默认
                if (json["inOutType"].ToString()=="pibg" || json["inOutType"].ToString() == "pobg")
                {
                    scan.inOutType = json["ioTypeCode"].ToString();
                    scan.operateCode = json["inOutType"].ToString();
                }

                oper = new OperateModel();
                oper.Data = scan;
                oper.Types = OperateModel.OperateType.Add;
                operList.Add(oper);
                rsl.Result = true;


                #endregion

            }
            catch (Exception ex)
            {
                rsl.Result = false;
                rsl.Message = ex.Message;
                return rsl;
            }
            return rsl;
        }

        /// <summary>
        /// 获取临时表中扫描的当前的条码信息
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult getScanBarCode(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                DataTable dt = new DataTable();
                string helperCode = string.Empty;
                string helperName = string.Empty;
                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                Dictionary<string, object> dic = new Dictionary<string, object>();
                List<OperateModel> sqlList = new List<OperateModel>();
                sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "参数不允许为空";
                    return rsl;
                }
                _log.Info("getScanBarCode方法参数：" + jsonStr);
                JObject json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                if (json.Property("inOutType") != null && !string.IsNullOrWhiteSpace(json["inOutType"].ToString()))
                {
                    if (json["inOutType"].ToString().Equals("pibg") || json["inOutType"].ToString().Equals("pobg"))
                    {
                        sb.Clear();
                        sb.Append("select byBarCode as barCode,byCode,banchang,banzhou,i.proName ");
                        sb.Append(" from fun_BanYang_list b ");
                        sb.Append(" inner join fun_Inventory_Info i on i.proCode=b.erpProCode ");
                        sb.Append("where b.baseCode='" + json["baseCode"].ToString() + "' ");
                        sb.Append(" and byBarCode='" + json["barCode"].ToString() + "'");
                        sb.Append(" and b.isdel=0 and dTypes='bg' ");
                    }
                    else
                    {
                        sb.Clear();
                        sb.Append("select bar.barCode, bar.planCode as plCode,bar.proCode,bar.proName,bar.number,bar.proWeight as weight, ");
                        sb.Append(" bar.barStatus,bar.proMeter as mishu,bar.U8relationCode,  "); // co.cName  goodsPositionName,
                        sb.Append("bar.cu_customer,cu.cuName customerName");
                        sb.Append(" from bar_ProductBarCode_info bar ");  
                        //sb.Append(" left join fun_CommonData_Info co on bar.warePosition=co.cCode and cType='WP' and co.isdel=0  ");
                        sb.Append(" left join fun_Customs_info cu on bar.cu_customer=cu.cuCode and cu.dataType = 'Cu' and cu.isDel=0  ");
                        sb.Append(" and cu.baseCode='" + json["baseCode"].ToString() + "' ");
                        sb.Append("where bar.barCode='" + json["barCode"].ToString() + "'");
                    }
                }
                dt = cmd.GetDataTable(sb.ToString());

                if (dt != null && dt.Rows.Count > 0)
                {

                    var scanList = cmd.TableToDictionary(dt);
                    Dictionary<string, string> temdic = new Dictionary<string, string>();
                    if (json.Property("inOutType") != null && !string.IsNullOrWhiteSpace(json["inOutType"].ToString()))
                    {
                        if (json["inOutType"].ToString().Equals("pibg") || json["inOutType"].ToString().Equals("pobg"))
                        {
                            temdic.Add("barCode", "存货编码");
                            temdic.Add("byCode", "版号");
                            temdic.Add("proName", "存货名称");
                            temdic.Add("banchang", "版长");
                            temdic.Add("banzhou", "版周");
                            //temdic.Add("banzhi", "版支数");
                            //temdic.Add("banhao", "版号");
                            //temdic.Add("weizhi", "位置");
                            //temdic.Add("customName", "客户名称");
                            //temdic.Add("zbcjName", "制版厂家");
                            //temdic.Add("bstatusName", "条码状态");
                        }
                        else if (json["inOutType"].ToString().Equals("piyb") || json["inOutType"].ToString().Equals("poyb"))
                        {
                            temdic.Add("barCode", "条码编码");
                            temdic.Add("yName", "样版名称");
                            temdic.Add("shuliang", "数量");
                            temdic.Add("weizhi", "位置");
                            temdic.Add("proCount", "存货数量");
                            temdic.Add("ystatusName", "条码状态");
                        }
                        else
                        {
                            temdic.Add("barCode", "条码编码");
                            temdic.Add("customerName", "客户名称");
                            temdic.Add("plCode", "生产单号");
                            temdic.Add("number", "数量");
                            //temdic.Add("barList", "明细信息");
                        }
                    }
                    scanList.Insert(0, temdic);
                    dic.Add("scanList", scanList);
                    list.Add(dic);
                    rsl.Data = list;
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "没有该扫描条码的数据";
                    rsl.Result = false;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除重复数据(出入库)
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult DelCollectRepeat(string jsonStr)
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                var obj = JsonConvert.DeserializeObject<JObject>(jsonStr);
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "传递参数有误";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("delete from bar_TempScanData_info where ");
                //if (isBoxCode(obj["barCode"].ToString()))
                //{
                //    sb.Append("boxCode='" + obj["barCode"] + "'");
                //}
                //else
                //{

                //}
                sb.Append("barCode='" + obj["barCode"].ToString() + "'");

                if (obj.Property("mobType") != null && !string.IsNullOrWhiteSpace(obj["mobType"].ToString()) && obj["mobType"].ToString().Equals("H5"))
                {
                    sb.Append(" and tempCode='" + obj["tempCode"].ToString() + "'");
                }
                rsl = cmd.UpdateSql(sb.ToString());
                if (rsl.Result)
                {
                    var barNumber = 0;
                    #region 获取该临时码中扫描的条码个数
                    sb.Clear();
                    sb.Append("select barCode,createuser from  bar_TempScanData_info ");
                    sb.Append("where tempCode='" + obj["tempCode"].ToString() + "'");
                    var scanTable = cmd.GetDataTable(sb.ToString());//获取扫描单下的所有扫描记录    
                    if (scanTable != null && scanTable.Rows.Count > 0)
                    {
                        barNumber = scanTable.Rows.Count;
                    }
                    var dic = new Dictionary<string, string>();
                    dic["barNumber"] = barNumber.ToString();
                    rsl.Data = dic;
                    #endregion
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            return rsl;
        }

        /// <summary>
        /// 保存临时数据
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult MSaveTempData(string jsonStr)
        {
            rsl = new ReturnResult();
            List<OperateModel> tempDelList = new List<OperateModel>();
            var proCodes = string.Empty;
            var tempcode = string.Empty;//临时编码号
            try
            {
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Result = false;
                    rsl.Message = "传递参数有误";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                var obj = JsonConvert.DeserializeObject<JObject>(jsonStr);
                var inOutTypeFalse = new[] { "pibg", "pifo", "pofo", "piyb", "poyb" };//虚拟出库类型  //,  "pobg"

                #region 根据临时编码获取到临时数据
                DbTempScanData temp = new DbTempScanData();
                if (!string.IsNullOrWhiteSpace(obj["tempCode"].ToString()))
                {
                    tempcode = obj["tempCode"].ToString();
                    temp.tempCode = tempcode;
                }
                else
                {
                    rsl.Message = "扫描单号不能为空";
                    rsl.Result = false;
                    return rsl;
                }

                var qList = cmd.GetDataByObject<DbTempScanData>(temp);

                foreach (var t in qList)
                {
                    if (t.wareHouse == t.targetWareHouse)
                    {
                        rsl.Message = "发生仓库与目标仓库相同！";
                        return rsl;
                    }
                }

                if (qList.Count < 1)
                {
                    rsl.Result = false;
                    rsl.Message = "没有要提交的数据";
                    return rsl;
                }
                #endregion

                _log.Info("tempScan表中数据：" + "临时单号：" + qList[0].tempCode + JsonConvert.SerializeObject(qList));

                /////////////////////////////////////////////////////////
                List<OperateModel> list = new List<OperateModel>();
                OperateModel oper;
                var planList = new DataTable();
                string mcode = DateTime.Now.ToString("yyyyMMddhhmmss");
                var lingyongCode = string.Empty;//领用编码
                var yuancailiaoku = string.Empty;//原材料库编码

                List<string> boxList = new List<string>();
                var barCodes = string.Empty;//所有的条码

                #region list数据保存 判断条码是否有效
                sb = new StringBuilder();
                if (obj["inOutType"].ToString().Equals("pobg") || obj["inOutType"].ToString().Equals("pibg"))
                {
                    sb.Append("select id,byCode,byBarCode proCode,byBarCode barCode,status barStatus,'1' number,wareHouse ");
                    sb.Append("from fun_BanYang_list where isdel=0 ");
                }
                else
                {
                    sb.Append("select id,proCode,barCode,barStatus,isnull(boxCode,'') boxCode,number ");
                    sb.Append("from bar_ProductBarCode_info ");
                    sb.Append("where barStatus not in ('bar-drop','used-finish') ");//感觉不加的话数据越来越多查的越来越慢
                    //,'bar-finish'
                }
                var table = cmd.GetDataTable(sb.ToString());

                foreach (var db in qList)
                {
                    #region 判断条码状态
                    var barCode = db.barCode;
                    var type = obj["inOutType"].ToString();
                    //改变状态为完成
                    var barStatus = string.Empty;//工序状态
                    var msg = string.Empty;

                    var rows = table.Select(" barCode='" + barCode + "' ");
                    if (rows.Length > 0)
                    {
                        string status = rows[0]["barStatus"].ToString();

                        //虚拟入库不需要判定状态
                        if (!inOutTypeFalse.Contains(type))
                        {
                            if (qList[0].operateType.ToLower() == "01")  //入库
                            {
                                #region 入库
                                //if (type.Equals("pio"))   //其他入
                                //{
                                //    if (status != "need-back")
                                //    {
                                //        rsl.Result = false;
                                //        rsl.Message = string.Format("此标签是" + new AppBLL().getBarStatus(status) + "不是待归还状态:{0}", barCode);
                                //        return rsl;
                                //    }
                                //}
                                //else
                                //{
                                if (qList[0].isBlue == "1")
                                {
                                    if (status != "need-in")
                                    {
                                        rsl.Result = false;
                                        rsl.Message = string.Format("此标签为" + new AppBLL().getBarStatus(status) + "禁止入库:{0}", barCode);
                                        return rsl;
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrWhiteSpace(status))
                                    {
                                        if (!status.Equals("need-out"))
                                        {
                                            rsl.Result = false;
                                            rsl.Message = string.Format("此标签状态为" + new AppBLL().getBarStatus(status) + "禁止做红单入库:{0}", barCode);
                                            return rsl;
                                        }
                                    }
                                }
                                //}
                                #endregion

                            }
                            else if (qList[0].operateType.ToLower() == "02") //出库
                            {
                                #region 出库
                                barCodes += db.barCode + ",";
                                if (qList[0].isBlue == "1")
                                {
                                    if (obj["inOutType"].ToString().Equals("pom"))
                                    {
                                        if (!status.Equals("bar-used") && !status.Equals("need-out"))
                                        {
                                            rsl.Result = false;
                                            rsl.Message = string.Format("此标签为" + new AppBLL().getBarStatus(status) + "禁止出库:{0}", barCode);
                                            return rsl;
                                        }
                                    }
                                    else
                                    {
                                        if (status != "need-out")
                                        {
                                            rsl.Result = false;
                                            rsl.Message = string.Format("此标签为" + new AppBLL().getBarStatus(status) + "禁止出库:{0}", barCode);
                                            return rsl;
                                        }
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrWhiteSpace(status))
                                    {
                                        if (!status.Equals("bar-finish"))
                                        {
                                            rsl.Result = false;
                                            rsl.Message = string.Format("此标签为" + new AppBLL().getBarStatus(status) + "禁止做红单出库:{0}", barCode);
                                            return rsl;
                                        }
                                    }
                                }
                                #endregion

                            }
                            else if (qList[0].operateType.ToLower() == "03")  //调拨、货位调整
                            {
                                #region 调拨
                                if (status != "need-out")
                                {
                                    rsl.Result = false;
                                    rsl.Message = string.Format("此标签为" + new AppBLL().getBarStatus(status) + "禁止调拨库:{0}", barCode);
                                    return rsl;
                                }
                                #endregion

                            }
                        }
                        else
                        {
                            //虚拟入库中，版辊入库判断仓库不是版库，不用入库了
                            if (type == "pibg")
                            {
                                var work_sql = "select parValue from sys_parameters_info where parCode = 'pibg_Ware_Style' ";
                                var wt = cmd.GetDataTable(work_sql);   //获取版库编码
                                var workCode = "004";
                                if (wt.Rows.Count > 0)
                                    workCode = wt.Rows[0]["parValue"].ToString();

                                if(rows[0]["wareHouse"].ToString()== workCode)
                                {
                                    rsl.Result = false;
                                    rsl.Message = string.Format("此标签已在版库，禁止重复入库:{0}", barCode);
                                    return rsl;
                                }

                            }
                        }


                    }
                    else
                    {
                        rsl.Result = false;
                        rsl.Message = string.Format("标签已作废或已使用完成:{0}", barCode);
                        return rsl;
                    }
                    #endregion
                }
                #endregion



                #region 生成U8单据
                U8Order uOrder = new U8Order();

                var uCode = obj["createuser"].ToString();
                var baseCode = obj["baseCode"].ToString();

                if (qList[0].operateType == "01")
                {
                    //产成品入库类型
                    if (obj["inOutType"].ToString().Equals("piw"))
                    {
                        rsl = uOrder.productIn(qList, baseCode, uCode);
                    }
                    //采购入库
                    if (obj["inOutType"].ToString().Equals("pic"))
                    {
                        //rsl = uOrder.OtherInWareHouse(qList, obj["baseName"].ToString(), mcode);
                    }
                    //其它入库
                    if (obj["inOutType"].ToString().Equals("pio"))
                    {
                        rsl = uOrder.OtherIn(qList, baseCode, uCode);
                    }

                }
                else if (qList[0].operateType == "02")
                {
                    #region 出库操作
                    if (obj["inOutType"].ToString().Equals("pom"))
                    {   //材料出库
                        var sql = "select parValue from sys_parameters_info where parCode='spPOMType' and isDel=0 and enable='open' ";
                        var t = cmd.GetDataTable(sql);
                        var spCode = "999";//材料出库中需要做调拨单的 出库类型
                        if(t.Rows.Count > 0)
                        {
                            spCode = t.Rows[0]["parValue"].ToString();
                        }
                        if (qList[0].typeCode.Equals(spCode))
                        {
                            rsl= uOrder.WareHouseChanage(qList, baseCode, uCode,spCode);  //做调拨
                        }
                        else
                        {
                            rsl = uOrder.MaterialOut(qList, baseCode, uCode);   //做材料出库
                        }
                    }
                    else if (obj["inOutType"].ToString().Equals("pobg"))
                    { //版辊(材料)出库
                        rsl = uOrder.MaterialOut(qList, baseCode, uCode);
                    }
                    else if (obj["inOutType"].ToString().Equals("pos"))
                    {//销售出库
                        rsl = uOrder.SaleOut(qList, baseCode, uCode);
                    }
                    else if (obj["inOutType"].ToString().Equals("poo"))
                    { //其它出库
                        rsl = uOrder.OtherOut(qList, baseCode, uCode);
                    }
                    #endregion
                }
                else if (qList[0].operateType == "03")
                {
                    //var pawList = new string[] { "paw", "pawcp", "pawll" };
                    //仓库调拨
                    //if (pawList.Contains(obj["inOutType"].ToString()))
                    if (obj["inOutType"].ToString().Equals("paw"))
                    {
                        rsl = uOrder.WareHouseChanage(qList, baseCode, uCode);
                    }
                    /**货位调整(不存在货位调整情况)
                    if (obj["inOutType"].ToString().Equals("pag"))
                    {
                        //rsl = uOrder.GoodsPositionChanage(qList, baseCode, uCode);
                    }
                    **/



                }
                #endregion

                #region 调用U8接口返回的数据
                var tempbarCodes = string.Empty;//存入到出入库列表中的条码
                var U8Code = string.Empty;
                var U8Message = string.Empty;
                var U8Codes = string.Empty;
                var errBarCodes = new List<string>();//调用接口失败的条码



                //虚拟出入库类型
                if (inOutTypeFalse.Contains(obj["inOutType"].ToString()))
                {
                    U8Code = "01";
                    U8Codes += U8Code + ",";
                    #region 构建参数数组
                    var cCode = getTimeString();//单据的临时编码
                    Dictionary<string, object> tempdic = new Dictionary<string, object>();
                    tempdic.Add("mCode", cCode);//临时编码
                    if (obj["inOutType"].ToString() == "pibg" || obj["inOutType"].ToString() == "pobg")
                    {
                        tempdic.Add("inOutType", obj["ioTypeCode"].ToString());
                    }
                    else
                    {
                        tempdic.Add("inOutType", obj["inOutType"].ToString());
                    }
                    tempdic.Add("type", obj["inOutType"].ToString());
                    tempdic.Add("outOrderCode", U8Code);//U8单号
                    tempdic.Add("baseCode", obj["baseCode"].ToString());
                    tempdic.Add("barList", null);
                    #endregion
                    #region 添加主表和子表出入库记录
                    insertMain(tempdic, qList, ref list);
                    rsl = insertList(tempdic, qList, ref list, ref tempbarCodes, null);
                    if (!rsl.Result)
                    {
                        return rsl;
                    }
                    #endregion
                }
                else
                {
                    if (!rsl.Result)
                    {
                        rsl.Result = false;
                        var message = "接口返回的单据号为空" + "\n";
                        if (rsl.Message != null && !string.IsNullOrWhiteSpace(rsl.Message.ToString()))
                        {
                            message += "U8错误：" + rsl.Message.ToString();//U8返回来的错误信息
                        }
                        rsl.Message = message;
                        _log.Info("生成单据失败:" + message);
                        return rsl;
                    }
                    #region 添加出入库记录
                    if (rsl.Data != null)
                    {
                        List<InOutResult> iorList = new List<InOutResult>();
                        iorList = (List<InOutResult>)rsl.Data;
                        if (iorList.Count > 0)
                        {
                            U8Codes = "";
                            foreach (InOutResult ior in iorList)
                            {
                                if (!string.IsNullOrWhiteSpace(ior.SuccOrderCode))
                                {
                                    #region 调用接口成功
                                    U8Codes += ior.SuccOrderCode + ",";
                                    #region 构建参数数组
                                    var barList = ior.SuccBarCodes;
                                    var cCode = getTimeString();//单据的临时编码
                                    Dictionary<string, object> tempdic = new Dictionary<string, object>();
                                    tempdic.Add("mCode", cCode);//临时编码
                                    if(obj["inOutType"].ToString()=="pibg" || obj["inOutType"].ToString()=="pobg")
                                        tempdic.Add("inOutType", obj["ioTypeCode"].ToString());
                                    else
                                        tempdic.Add("inOutType", obj["inOutType"].ToString());

                                    tempdic.Add("type", obj["inOutType"].ToString());
                                    tempdic.Add("outOrderCode", ior.SuccOrderCode);//U8单号
                                    tempdic.Add("baseCode", obj["baseCode"].ToString());
                                    tempdic.Add("barList", barList);
                                    #endregion
                                    #region 添加主表和子表出入库记录    修改条码状态，添加计划用料信息
                                    insertMain(tempdic, qList, ref list);
                                    rsl = insertList(tempdic, qList, ref list, ref tempbarCodes, null);
                                    if (!rsl.Result)
                                    {
                                        return rsl;
                                    }
                                    #endregion

                                    #region 返回错误信息和错误条码
                                    ErrorResult err = (ErrorResult)ior.ErrorInfo;
                                    if (err != null)
                                    {
                                        if (!string.IsNullOrWhiteSpace(err.ErrorMsg))
                                        {
                                            U8Message += JsonConvert.SerializeObject(err.BarCodes) + "：" + err.ErrorMsg + "\n";//U8返回来的错误信息
                                        }
                                    }
                                    #endregion

                                    #endregion
                                }
                                else
                                {
                                    #region 返回错误信息和错误条码
                                    ErrorResult err = (ErrorResult)ior.ErrorInfo;
                                    if (err != null)
                                    {
                                        if (!string.IsNullOrWhiteSpace(err.ErrorMsg))
                                        {
                                            U8Message += JsonConvert.SerializeObject(err.BarCodes) + "：" + err.ErrorMsg + "\n";//U8返回来的错误信息
                                        }
                                        if (err.BarCodes != null && err.BarCodes.Count > 0)
                                        {
                                            errBarCodes.AddRange(err.BarCodes);
                                        }
                                    }
                                    #endregion
                                }
                            }
                        }
                    }
                    #endregion
                }
                #endregion

                #region 删除临时条码
                var inOutType = obj["inOutType"].ToString(); //出入库类型
                if(inOutType == "pibg" || inOutType == "pobg")
                {
                    inOutType = obj["ioTypeCode"].ToString();
                }
                delteTempCode(qList, ref list, errBarCodes, inOutType);
                #endregion

                #region 成品入库时判断  如果条码的存货 和 计划存货 不匹配，则清空条码的costPlan值
                if(inOutType == "piw" )
                {
                    var barcode = tempbarCodes.Split(',');  //成功入库的条码
                    if (barcode.Length > 0)
                    {
                        var barTable = new DataTable();
                        sb = new StringBuilder();
                        sb.Append("seleCt b.barCode,b.proCode ");
                        sb.Append(",b.planCode,p.proCode planProCode,  b.costPlan ");
                        sb.Append("from bar_ProductBarCode_info b ");
                        sb.Append("inner join pi_ProductionPlan_info  p on b.planCode=p.plCode and p.isdel='0' ");

                        var sql = sb.ToString();

                        foreach (var bar in barcode)
                        {
                            if (!string.IsNullOrWhiteSpace(bar))
                            {
                                sb.Clear();
                                sb.Append(sql + " where b.barCode='" + bar + "'");
                                barTable = cmd.GetDataTable(sb.ToString());

                                if (barTable.Rows.Count > 0)
                                {
                                    if (!barTable.Rows[0]["proCode"].ToString().Equals(barTable.Rows[0]["planProCode"].ToString()))
                                    {
                                        //清空条码的costPlan值
                                        DbProductBarCode b = new DbProductBarCode();
                                        b.barCode = bar;
                                        b.costPlan = "-";

                                        oper = new OperateModel();
                                        oper.Data = b;
                                        oper.Types = OperateModel.OperateType.Edit;
                                        oper.Conditions = "barCode";

                                        list.Add(oper);
                                    }
                                }
                            }

                        }
                    }
                }
                #endregion

                #region 执行修改语句
                rsl = cmd.MoreUpdate(list);
                if (!rsl.Result)
                {
                    var temRsl = rsl;
                    return temRsl;
                }
                #endregion

                if (!string.IsNullOrWhiteSpace(U8Message))
                {
                    U8Message = "U8接口错误：" + U8Message;
                }
                var U8cCode = "";
                if (!string.IsNullOrWhiteSpace(U8Codes))
                {
                    U8cCode = "保存成功，单号为：" + U8Codes.TrimEnd(',');
                }
                rsl.Result = true;
                rsl.Data = U8cCode;
                rsl.Message = U8Message;
                //}
                ///////////////////////////////////////////////////////////
            }
            catch (Exception ex)
            {
                #region 发生错误后删除已添加到临时表中没有条码的数据
                rsl = cmd.MoreUpdate(tempDelList);
                if (!rsl.Result)
                {
                    _log.Info("临时单号：" + tempcode + "删除材料出库时添加的没有条码的数据失败");
                    return rsl;
                }
                #endregion
                rsl.Result = false;
                rsl.Message = ex.Message;
                _log.Info("生成单据异常:" + rsl.Message);
                return rsl;
            }
            return rsl;
        }

        /// <summary>
        /// 生成销售信息表模型
        /// </summary>
        /// <param name="barCodes">一系列条码，用英文逗号隔开</param>
        /// <param name="cuCode">客户编码</param>
        /// <param name="salesDepartment">销售人员名称（实际业务员），不是销售部门编码</param>
        /// <param name="models">【引用传递】操作模型列表。如果列表内已经有对象，则追加对象。如果列表为Null，则自动新建列表。</param>
        /// <param name="errorMessage">【引用传递】传入空字符串。如果返回字符串非空，则表示方法执行失败。</param>
        public void FillSalesRecords(string barCodes, string cuCode, string salesDepartment, string createuser,ref List<OperateModel> models, ref string errorMessage)
        {
            try
            {
                if (models == null)
                {
                    models = new List<OperateModel>();
                }

                var internalModelList = new List<OperateModel>();
                var barArray = barCodes.Split(',');
                foreach (var bar in barArray)
                {
                    if (string.IsNullOrWhiteSpace(bar))
                    {
                        continue;
                    }
                    var rec = new DbSalesRecords();
                    rec.salesDate = DateTime.Now.ToString("yyyy-MM-dd");
                    rec.barCode = bar;
                    rec.cuCode = cuCode;
                    rec.createtime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    rec.createuser = createuser;
                    rec.status = "Y";
                    rec.isDel = "0";
                    rec.salesStaff = salesDepartment;

                    var operModel = new OperateModel();
                    operModel.Data = rec;
                    operModel.Types = OperateModel.OperateType.Add;
                    internalModelList.Add(operModel);
                }

                models.AddRange(internalModelList);
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }
        }

        /// <summary>
        /// 出入库记录单主表
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="qList"></param>
        /// <param name="list"></param>
        public void insertMain(Dictionary<string, object> dic, List<DbTempScanData> qList, ref List<OperateModel> list,string isFrom=null)
        {
            try
            {
                #region 反写出入库记录的主表
                var type = dic["type"].ToString();//操作类型
                var inOutType = dic["inOutType"].ToString();//出入库类型
                var mCode = dic["mCode"].ToString();//临时编码
                var outOrderCode = dic["outOrderCode"].ToString();//反写的单据号
                var baseCode = dic["baseCode"].ToString();//
                DbBarRecordsMain main = new DbBarRecordsMain();
                main.happenDate = qList[0].happenDate;
                main.wareHouse = qList[0].wareHouse;
                main.isBlue = qList[0].isBlue;
                main.createuser = qList[0].createuser;
                main.mType = qList[0].typeCode;
                main.deptCode = qList[0].operateDept;
                main.createtime = getNow();
                main.baseCode = baseCode;
                main.status = "needAudit";
                main.isCount= 0;
                main.maker = qList[0].createuser;
                main.inOutType = inOutType;
                main.referOrderCode = qList[0].outOrderCode;//关联U8单据号 /关联计划单号
                main.outOrderCode = outOrderCode;//反写的出入库单据号
                if (type == "pibg" || type == "pobg")
                    main.customCode = qList[0].barCode;
                else
                    main.customCode = qList[0].customCode;
                //main.goodsPosition = qList[0].goodsPosition;//发生货位
                var pawList = new string[] { "paw", "pawcp", "pawll" };
                //仓库调拨
                if (pawList.Contains(type))
                {
                    main.targetWareHouse = qList[0].targetWareHouse;//目标仓库
                }
                //货位调拨
                if (type.Equals("pag"))
                {
                    main.targetGoodsPosition = qList[0].targetGoodsPosition;//目标货位
                                                                            //main.targetGoodsPosition = qList[0].targetGoodsPosition;//目标货位
                }
                main.mCode = mCode;//主表的临时码
                if (string.IsNullOrEmpty(isFrom))
                    main.isForm = "app";//数据来源
                else
                    main.isForm = isFrom;//数据来源
                if (qList[0].memo != null && !string.IsNullOrEmpty(qList[0].memo.ToString()))
                {
                    main.memo = qList[0].memo.ToString();
                }
                OperateModel oper = new OperateModel();
                oper.Data = main;
                oper.Types = OperateModel.OperateType.Add;
                list.Add(oper);
                _log.Info("反写出入库记录主表单据号：" + mCode);
                #endregion
            }
            catch (Exception ex)
            {
                return;
            }
        }

        /// <summary>
        /// 出入库记录子表
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="qList"></param>
        /// <param name="list"></param>
        /// <param name="barCodes"></param>
        /// <param name="erridList"></param>
        /// <returns></returns>
        public ReturnResult insertList(Dictionary<string, object> dic, List<DbTempScanData> qList, ref List<OperateModel> list, ref string barCodes, List<string> erridList)
        {
            try
            {
                #region 反写出入库单据明细表的数据
                var type = dic["type"].ToString();//操作类型
                var inOutType = dic["inOutType"].ToString();//出入库类型
                var mCode = dic["mCode"].ToString();//临时编码
                var outOrderCode = dic["outOrderCode"].ToString();//反写的单据号
                var baseCode = dic["baseCode"].ToString();
                var barList = (List<string>)dic["barList"];
                rsl = new ReturnResult();
                foreach (var db in qList)
                {
                    string barCode = db.barCode;
                    if (barList != null && !barList.Contains(barCode))
                    {
                        continue;
                    }

                    #region 改变条码/版辊的状态
                    if (type == "pibg" || type == "pobg")
                    {
                        rsl = updateBanGunStatus(barCode, db, ref list, qList, type);
                    }
                    else
                    {
                        rsl = updateBarCodeStatus(barCode, db, ref list, qList, type);
                    }
                    if (!rsl.Result)
                    {
                        return rsl;
                    }
                    #endregion

                    #region 调拨时，更新占用记录中的条码库位
                    if (inOutType.Equals("paw") && !string.IsNullOrEmpty(qList[0].outOrderCode))
                    {
                        DbProductsOccupation po = new DbProductsOccupation();
                        po.barCode= barCode;
                        po.plCode = db.outOrderCode;
                        po.wareHouse=db.targetWareHouse;
                        OperateModel oper = new OperateModel();
                        oper.Data = po;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "barCode,plCode";
                        list.Add(oper);
                    }
                    #endregion

                    StringBuilder sb = new StringBuilder();
                    if (type == "pibg" || type == "pobg")
                    {
                        sb.Append("select id,byCode ,byBarCode proCode,status barStatus,'1' number ,'' cu_batch ");
                        sb.Append("from fun_BanYang_list where byBarCode='" + barCode + "'");
                    }
                    else
                    {
                        sb.Append("select id,proCode,cu_batch,barCode,barStatus,isnull(boxCode,'') boxCode,number ");
                        sb.Append("from bar_ProductBarCode_info where barCode='" + barCode + "'");
                    }

                    var t = cmd.GetDataTable(sb.ToString());
                    if (t.Rows.Count > 0)
                    {
                        var proCode = t.Rows[0]["proCode"].ToString();
                        var batch = t.Rows[0]["cu_batch"].ToString();

                        #region 物控生产计划单 绑定条码使用 
                        if ((type.Equals("pom") && qList[0].typeCode!="999") || (type.Equals("pobg") && inOutType == "scsy"))  //生产使用时改变版辊关联的计划
                        {
                            //添加生产计划使用的条码
                            rsl = saveBarCodePlan(barCode, proCode, batch, ref list, db, mCode);
                            if (!rsl.Result)
                            {
                                return rsl;
                            }
                        }
                        #endregion

                        #region 出入库记录子表
                        DbBarRecordsList dl = new DbBarRecordsList();
                        dl.barCode = barCode;
                        dl.mCode = mCode;//主表临时编码
                        dl.status = "Y";
                        dl.createuser = qList[0].createuser;
                        var listCount = cmd.GetDataByObject<DbBarRecordsList>(dl).Count;
                        if (listCount <= 0)
                        {
                            var barcode = barCodes.Split(',');
                            if (!barcode.Contains(barCode))
                            {
                                barCodes += barCode + ",";
                                #region list数据
                                dl = new DbBarRecordsList();
                                dl.barCode = barCode;
                                dl.createtime = getNow();
                                dl.mCode = mCode;//主表临时编码
                                dl.num = t.Rows[0]["number"].ToString();
                                dl.inOutType = inOutType;
                                dl.status = "Y";
                                dl.goodsPosition = db.goodsPosition;
                                var pawList = new string[] { "paw", "pawcp", "pawll", "pag" };
                                //仓库调拨//货位调拨
                                if (pawList.Contains(type))
                                {
                                    dl.targetGoodsPosition = db.targetGoodsPosition;//目标货位
                                }
                                dl.createuser = qList[0].createuser;
                                OperateModel oper = new OperateModel();
                                oper.Data = dl;
                                oper.Types = OperateModel.OperateType.Add;
                                list.Add(oper);
                                #endregion
                            }
                        }

                        #endregion

                        rsl.Result = true;
                    }
                    else
                    {
                        rsl.Result = false;
                        rsl.Message = string.Format("标签记录不存在：{0}", barCode);
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 改变条码状态
        /// </summary>
        /// <param name="barCode"></param>
        /// <param name="list"></param>
        /// <param name="qList"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private ReturnResult updateBarCodeStatus(string barCode, DbTempScanData db, ref List<OperateModel> list, List<DbTempScanData> qList, string type)
        {
            rsl = new ReturnResult();
            OperateModel oper = new OperateModel();
            StringBuilder sb = new StringBuilder();
            try
            {
                sb.Append("select id,proCode,barCode,barStatus,isnull(boxCode,'') boxCode,number ");
                sb.Append("from bar_ProductBarCode_info where barCode='" + barCode + "'");
                var t = cmd.GetDataTable(sb.ToString());
                if (t.Rows.Count > 0)
                {
                    string status = t.Rows[0]["barStatus"].ToString();
                    //var arr = main.mType.Split('-');
                    //改变状态为完成
                    var barStatus = string.Empty;//工序状态
                    var msg = string.Empty;
                    #region 改变条码状态
                    DbProductBarCode barInfo;
                    if (qList[0].operateType.ToLower() == "01")
                    {
                        #region 改变标签状态为待出库状态
                        //改变状态为完成
                        barStatus = string.Empty;//工序状态
                        msg = string.Empty;
                        //获取该条码的下一道工序
                        barStatus = "need-out";
                        if (!string.IsNullOrWhiteSpace(msg) && !msg.Contains("强制完成"))
                        {
                            rsl.Result = false;
                            rsl.Message = msg;
                            return rsl;
                        }
                        if (!string.IsNullOrWhiteSpace(barStatus))
                        {
                            barInfo = new DbProductBarCode();
                            barInfo.Id = int.Parse(t.Rows[0]["id"].ToString());
                            //蓝单
                            if (qList[0].isBlue == "1")
                            {
                                barInfo.barStatus = barStatus;
                                barInfo.wareHouse = db.wareHouse;
                                barInfo.warePosition = db.goodsPosition;
                            }
                            else
                            {
                                barInfo.barStatus = "need-in";
                                barInfo.wareHouse = "-";
                                barInfo.warePosition = "-";
                            }
                            barInfo.memo = msg;
                            oper = new OperateModel();
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Data = barInfo;
                            oper.Conditions = "Id";
                            list.Add(oper);
                        }
                        #endregion
                    }
                    else if (qList[0].operateType.ToLower() == "02")
                    {
                        #region 改变条码状态
                        //改变状态为完成
                        barStatus = string.Empty;//工序状态
                        msg = string.Empty;
                        barStatus = "bar-finish";
                        if (type.Equals("pom"))
                        {//材料出库或版辊出库 修改为生产使用
                            barStatus = "bar-used";
                        }
                        if (!string.IsNullOrWhiteSpace(msg) && !msg.Contains("强制完成"))
                        {
                            rsl.Result = false;
                            rsl.Message = msg;
                            return rsl;
                        }
                        if (!string.IsNullOrWhiteSpace(barStatus))
                        {
                            barInfo = new DbProductBarCode();
                            barInfo.Id = int.Parse(t.Rows[0]["Id"].ToString());
                            if (qList[0].isBlue == "1")
                            {
                                #region 999时，生成的调拨单
                                if (db.typeCode == "999")
                                {
                                    barInfo.barStatus = "need-out";
                                    barInfo.warePosition = "-";
                                    barInfo.wareHouse = "8";
                                }
                                else
                                {
                                    barInfo.barStatus = barStatus;
                                    barInfo.warePosition = "-";
                                    barInfo.wareHouse = "-";//出库时 标签所属仓库清空(如考虑数量需要重新更改此处代码)
                                }
                                #endregion
                            }
                            else
                            {
                                barInfo.barStatus = "need-out";
                                barInfo.wareHouse = db.wareHouse;
                                barInfo.warePosition = db.goodsPosition;
                            }
                            barInfo.memo = msg;
                            oper = new OperateModel();
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Data = barInfo;
                            oper.Conditions = "Id";
                            list.Add(oper);
                        }
                        #endregion
                    }
                    else if (qList[0].operateType.ToLower() == "03")
                    {
                        #region 改变条码状态
                        //改变状态为完成
                        barStatus = string.Empty;//工序状态
                        msg = string.Empty;
                        //获取该条码的下一道工序
                        barInfo = new DbProductBarCode();
                        barInfo.Id = int.Parse(t.Rows[0]["Id"].ToString());
                        var pawList = new string[] { "paw", "pawcp", "pawll" };
                        //仓库调拨
                        if (pawList.Contains(type))
                        {
                            barInfo.wareHouse = db.targetWareHouse;
                            if (string.IsNullOrWhiteSpace(db.targetGoodsPosition))
                            {
                                barInfo.warePosition = "-";
                            }
                            else
                            {
                                barInfo.warePosition = db.targetGoodsPosition;
                            }
                        }
                        if (type.Equals("pag"))
                        {
                            barInfo.warePosition = db.targetGoodsPosition;
                        }
                        barInfo.memo = msg;
                        oper = new OperateModel();
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Data = barInfo;
                        oper.Conditions = "Id";
                        list.Add(oper);
                        #endregion
                    }
                    #endregion
                }
                else
                {
                    rsl.Result = false;
                    rsl.Message = string.Format("标签记录不存在：{0}", barCode);
                    return rsl;
                }
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 改变版辊状态
        /// </summary>
        /// <param name="barCode"></param>
        /// <param name="list"></param>
        /// <param name="qList"></param>
        /// <param name="type"></param> //出入库类型
        /// <param name="inOutType"></param> //版辊出入库类型
        /// <returns></returns>
        private ReturnResult updateBanGunStatus(string barCode, DbTempScanData db, ref List<OperateModel> list, List<DbTempScanData> qList, string type)
        {
            rsl = new ReturnResult();
            OperateModel oper = new OperateModel();
            StringBuilder sb = new StringBuilder();
            try
            {
                sb.Append("select id,byCode,byBarCode,status,PPlan ");
                sb.Append("from fun_BanYang_list where byBarCode='" + barCode + "'");
                var t = cmd.GetDataTable(sb.ToString());
                if (t.Rows.Count > 0)
                {
                    string status = t.Rows[0]["status"].ToString();
                    string plCode = t.Rows[0]["PPlan"].ToString();

                    //改变状态为生产使用
                    var msg = string.Empty;

                    #region 改变版辊状态
                    DbBanGun barInfo;
                    if (qList[0].operateType.ToLower() == "01")
                    {
                        #region 改变标签状态为待出库状态
                        if (type.Equals("pibg"))
                        {
                            //改变状态为待出库

                            status = string.Empty;//状态
                            msg = string.Empty;
                            status = "need-out";
                            if (!string.IsNullOrWhiteSpace(msg) && !msg.Contains("强制完成"))
                            {
                                rsl.Result = false;
                                rsl.Message = msg;
                                return rsl;
                            }
                            if (!string.IsNullOrWhiteSpace(status))
                            {
                                barInfo = new DbBanGun();
                                barInfo.id = int.Parse(t.Rows[0]["id"].ToString());
                                //蓝单
                                if (qList[0].isBlue == "1")
                                {
                                    barInfo.status = status;
                                    barInfo.wareHouse = db.wareHouse;
                                }
                                else
                                {
                                    barInfo.status = "need-in";
                                    barInfo.wareHouse = "-";
                                }
                                barInfo.isfb = "0";//入库了之后就不算废版了
                                oper = new OperateModel();
                                oper.Types = OperateModel.OperateType.Edit;
                                oper.Data = barInfo;
                                oper.Conditions = "Id";
                                list.Add(oper);
                            }
                        }

                        #endregion
                    }
                    else if (qList[0].operateType.ToLower() == "02")
                    {
                        #region 改变版辊状态
                        if (type.Equals("pobg"))
                        {
                            #region 改变状态为待入库

                            status = string.Empty;//工序状态
                            msg = string.Empty;
                            status = "need-in";

                            if (!string.IsNullOrWhiteSpace(msg) && !msg.Contains("强制完成"))
                            {
                                rsl.Result = false;
                                rsl.Message = msg;
                                return rsl;
                            }

                            if (!string.IsNullOrWhiteSpace(status))
                            {

                                barInfo = new DbBanGun();
                                barInfo.id = int.Parse(t.Rows[0]["Id"].ToString());
                                if (qList[0].inOutType == "fbck" || qList[0].inOutType == "gbck")
                                {
                                    //如果是废版出库或改版出库 将版辊算成废版
                                    barInfo.isfb = "1";
                                }
                                if (qList[0].isBlue == "1")
                                {
                                    if (string.IsNullOrWhiteSpace(plCode))
                                    {
                                        barInfo.PPlan = db.outOrderCode;  //第一次出库时记录计划号
                                    }

                                    barInfo.status = status;
                                    barInfo.wareHouse = "-";//出库时 标签所属仓库清空(如考虑数量需要重新更改此处代码)
                                }
                                else
                                {
                                    barInfo.status = "need-out";
                                    barInfo.wareHouse = db.wareHouse;
                                }
                                oper = new OperateModel();
                                oper.Types = OperateModel.OperateType.Edit;
                                oper.Data = barInfo;
                                oper.Conditions = "Id";
                                list.Add(oper);
                            }
                            #endregion
                        }
                        #endregion
                    }

                    #endregion
                }
                else
                {
                    rsl.Result = false;
                    rsl.Message = string.Format("标签记录不存在：{0}", barCode);
                    return rsl;
                }
                rsl.Result = true;
                
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 添加生产计划对条码的使用
        /// </summary>
        /// <returns></returns>
        public ReturnResult saveBarCodePlan(string barCode, string proCode, string batch, ref List<OperateModel> list, DbTempScanData qList, string mCode)
        {
            rsl = new ReturnResult();
            #region 绑定条码的生产计划单
            try
            {
                PlanBLL plan = new PlanBLL();
                DBPlanYongLiao po = new DBPlanYongLiao();
                if (!string.IsNullOrWhiteSpace(qList.outOrderCode.ToString()))
                {
                    po.plCode = qList.outOrderCode;
                    po.proCode = proCode;
                    po.batch = batch;
                    po.reBarCode = barCode;
                    po.number = qList.number;
                    po.uPrice = plan.getProUprice(proCode, batch);
                    po.total = (decimal.Parse(qList.number) * decimal.Parse(po.uPrice)).ToString();
                    po.mType = "ymyl";  //有码用料
                    if (qList.isBlue == "1")
                        po.valueType = "1"; //正数
                    else
                        po.valueType = "-1";  //负数

                    po.mCode = mCode;
                    OperateModel oper = new OperateModel();
                    oper.Data = po;
                    oper.Types = OperateModel.OperateType.Add;
                    list.Add(oper);

                    rsl.Result = true;
                }
            }
            catch (Exception ex)
            {
                rsl.Result = false;
                rsl.Message = ex.Message;
                return rsl;
            }
            #endregion
            return rsl;
        }
       
        /// <summary>
        /// 删除临时数据
        /// </summary>
        /// <param name="qList"></param>
        /// <param name="list"></param>
        /// <param name="erridList"></param>
        /// <param name="type"></param>
        private void delteTempCode(List<DbTempScanData> qList, ref List<OperateModel> list, List<string> erridList, string type)
        {
            #region 删除临时数据
            if (qList.Count > 0)
            {
                foreach (DbTempScanData item in qList)
                {
                    if (erridList != null && erridList.Count > 0)
                    {
                        //错误的生产单号中包含的条码的不进行删除
                        //if (erridList.Contains(getBarCodePlan(item.barCode)))
                        //{
                        if (erridList.Contains(item.barCode))
                        {
                            continue;
                        }
                    }
                    DbTempScanData temp = new DbTempScanData();
                    temp.tempCode = item.tempCode;
                    temp.barCode = item.barCode;
                    temp.inOutType = type;
                    OperateModel oper = new OperateModel();
                    oper.Data = temp;
                    oper.Types = OperateModel.OperateType.Delete;
                    list.Add(oper);
                }
            }
            #endregion
        }























        /// <summary>
        /// 获取未处理任务数量(对应人员的)
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult getNTaskConfirmNum(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "传递的参数不能为空";
                    return rsl;
                }
                jsonStr = Encryption.DesDecrypt(jsonStr);
                var json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                var number = "0";
                if (json.Property("userCode") != null && !string.IsNullOrWhiteSpace(json["userCode"].ToString()))
                {
                    sb.Clear();
                    sb.Append("select count(ta.id) number from sys_TaskCenter_info ta ");
                    sb.Append(" inner join sys_dictionaries_info sys on sys.code=ta.businessType and sys.extendFile='taskType'");
                    sb.Append(" and sys.types='appTask' ");
                    sb.Append(" where 1=1 and ta.isFinish<>1  ");
                    sb.Append(" and toUser like '%" + json["userCode"].ToString() + "%'");
                    var dt = cmd.GetDataTable(sb.ToString());
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        number = dt.Rows[0]["number"].ToString();
                    }
                }
                rsl.Result = true;
                rsl.Data = number;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 获取任务中心列表
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult getTaskInfo(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "传递的参数不允许为空";
                    return rsl;
                }
                jsonStr = Encryption.DesDecrypt(jsonStr);
                var json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                sb.Clear();
                sb.Append("select *,case when isFinish=1 then '已处理' else '待处理' end finishType from V_TaskCenter ");
                var tableName = sb.ToString();
                sb.Clear();
                sb.Append(" 1=1 and sysTypes='appTask' ");
                if (json.Property("isFinish") != null && !string.IsNullOrWhiteSpace(json["isFinish"].ToString()))
                {
                    sb.Append(" and isFinish=" + json["isFinish"].ToString() + " ");
                }
                if (json.Property("date") != null && !string.IsNullOrWhiteSpace(json["date"].ToString()))
                {
                    sb.Append(" and convert(date,createtime)='" + json["date"].ToString() + "' ");
                }
                if (json.Property("createuser") != null && !string.IsNullOrWhiteSpace(json["createuser"].ToString()))
                {
                    sb.Append(" and toUser like'%" + json["createuser"].ToString() + "%'");
                }
                if (json.Property("businessType") != null && !string.IsNullOrWhiteSpace(json["businessType"].ToString()))
                {
                    sb.Append(" and businessType='" + json["businessType"].ToString() + "'");
                }
                var sqlWhere = sb.ToString();
                var orderStr = "createtime desc";

                #region 构建列表数据
                var dicList = new Dictionary<string, object>();
                #region 构建列表元素显示格式
                var headList = new List<object>();
                var hList = new List<Dictionary<string, string>>();
                createHead(ref hList, "taskCode", "任务单号");
                headList.Add(hList);
                hList = new List<Dictionary<string, string>>();
                createHead(ref hList, "businessTypeName", "任务类型");
                createHead(ref hList, "finishType", "状态");
                headList.Add(hList);
                hList = new List<Dictionary<string, string>>();
                createHead(ref hList, "createtime", "创建时间");
                headList.Add(hList);
                hList = new List<Dictionary<string, string>>();
                createHead(ref hList, "contents", "任务内容", "", "", true);
                headList.Add(hList);
                #endregion

                #region 数据分页显示
                //总条数
                var pageCount = "0";
                //总页数
                var pageNumber = "0";
                //每页条数
                var pageSize = "20";
                var paraList = cmd.getParam("appPageSize");
                if (paraList != null && paraList.Count > 0)
                {
                    if (!string.IsNullOrWhiteSpace(paraList[0].parValue))
                    {
                        pageSize = paraList[0].parValue;
                    }
                }
                #region 自动定位列表信息位置功能
                var table = new DataTable();
                var pageIndex = int.Parse(json["pageIndex"].ToString());
                if (json.Property("selectIndex") != null && !string.IsNullOrWhiteSpace(json["selectIndex"].ToString()) && int.Parse(json["selectIndex"].ToString()) > 0)
                {
                    var page = int.Parse(json["selectIndex"].ToString()) / int.Parse(pageSize);
                    var syCount = int.Parse(json["selectIndex"].ToString()) % int.Parse(pageSize);
                    if (syCount > 0)
                    {
                        page += 1;
                    }
                    var allCount = page * int.Parse(pageSize);//页数的总条数
                    //如果但前索引与到当前页所有数据的总条数相差5就再多请求一页数据；
                    if ((allCount - int.Parse(json["selectIndex"].ToString())) < 5)
                    {
                        page += 1;
                    }
                    //一次性请求的数据
                    var tempageNumber = "0";
                    var tempageCount = "0";
                    var tempageSize = (page * int.Parse(pageSize)).ToString();
                    table = cmd.PageTableList(tableName, "1", pageSize, sqlWhere, orderStr, ref pageCount, ref pageNumber);
                    table = cmd.PageTableList(tableName, "1", tempageSize, sqlWhere, orderStr, ref tempageCount, ref tempageNumber);
                    pageIndex = page;
                }
                else
                {
                    table = cmd.PageTableList(tableName, json["pageIndex"].ToString(), pageSize, sqlWhere, orderStr, ref pageCount, ref pageNumber);
                }
                #endregion

                #region 构建子表元素显示格式
                var headmxList = new List<object>();

                var hmxList = new List<Dictionary<string, string>>();
                createHead(ref hmxList, "tip01", "");
                createHead(ref hmxList, "tip02", "");
                headmxList.Add(hmxList);
                hmxList = new List<Dictionary<string, string>>();
                createHead(ref hmxList, "tip03", "");
                headmxList.Add(hmxList);


                #endregion
                var mxList = new List<object>();
                if (table != null && table.Rows.Count > 0)
                {
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        var item = table.Rows[i];
                        var temList = new List<Dictionary<string, string>>();
                        if (!string.IsNullOrWhiteSpace(item["details"].ToString()))
                        {
                            temList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(item["details"].ToString());

                        }

                        item["toUser"] = item["toUser"].ToString().TrimEnd(',');
                        mxList.Add(temList);
                    }
                }
                var temlist = cmd.TableToDictionary(table);
                #endregion
                var listInfo = new Dictionary<string, object>();
                listInfo.Add("head", headList);
                listInfo.Add("list", temlist);
                listInfo.Add("mxHead", headmxList);
                listInfo.Add("mxList", mxList);
                listInfo.Add("pageNumber", pageNumber);
                listInfo.Add("pageIndex", pageIndex.ToString());
                dicList.Add("listInfo", listInfo);
                #endregion
                rsl.Result = true;
                rsl.Data = dicList;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 任务中心中任务确认处理方法
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult taskConfirm(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "传递的参数不能为空";
                    return rsl;
                }
                
                var json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                #region 验证
                sb.Clear();
                sb.Append("select * from sys_TaskCenter_info where 1=1 ");
                sb.Append(" and id in (" + json["id"].ToString() + ") ");
                var taskDt = cmd.GetDataTable(sb.ToString());
                if (taskDt == null || taskDt.Rows.Count < 1)
                {
                    rsl.Message = "未找到相关任务信息";
                    return rsl;
                }

                foreach (DataRow  dr in taskDt.Rows)
                {
                    if (dr["isFinish"].ToString().Equals("1"))
                    {
                        rsl.Message = "选中任务包含已完成任务";
                        return rsl;
                    }
                }
                
                #endregion
                
                ////任务类型
                //var taskType = taskDt.Rows[0]["businessType"].ToString(); 
                var sqlList = new List<string>();

                #region 修改自动任务状态
                sb.Clear();
                sb.Append("update sys_TaskCenter_info set isFinish=1,finishDate='" + getNow() + "',finishUser='"+ json["createuser"].ToString() + "'");
                sb.Append(" where  id in (" + json["id"].ToString() + ")");
                sqlList.Add(sb.ToString());
                #endregion

                rsl = cmd.MoreUpdate(sqlList);
                if (!rsl.Result)
                {
                    rsl.Message = "任务处理失败";
                    return rsl;
                }
                else
                {
                    rsl.Message = "成功！" ;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }



        
    }
}